<template>
  <div class="w-full">
    <van-form @failed="onFailed">
      <van-cell-group inset>
        <van-field
          v-model="Info.name"
          placeholder="请输入姓名"
          label="姓名"
          name="姓名"
        />
        <van-field
          v-model="Info.mobile"
          name="pattern"
          placeholder="请输入手机号"
          label="手机号"
          :rules="[{ pattern, message: '请输入正确手机号' }]"
        />
        <van-field
          v-model="Info.joinAddress"
          is-link
          readonly
          label="地区"
          placeholder="请选择所在地区"
          @click="show = true"
        />
        <van-popup v-model:show="show" round position="bottom">
          <van-cascader
            v-model="cascaderValue"
            title="请选择所在地区"
            :options="options"
            @close="show = false"
            @finish="onFinish"
          />
        </van-popup>
        <van-field
          v-model="Info.address"
          placeholder="请输入详细地址"
          label="详细地址"
          name="详细地址"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button block type="primary" native-type="submit" @click="submit">
          保存
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<script setup>
import { useCascaderAreaData } from "@vant/area-data";
import { getAddress, editAddress } from "@/util/api";
import { showToast } from "vant";
import { useRouter } from "vue-router";
const show = ref(false);
const fieldValue = ref("");
const cascaderValue = ref("");
const options = useCascaderAreaData();
const pattern =
  /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
const Info = reactive({
  name: "",
  mobile: "",
  address: "", //地址详情
  province: "",
  city: "",
  area: "",
  joinAddress: "",
});
const router = useRouter();
const getDate = async () => {
  const res = await getAddress();
  for (let i in Info) {
    Info[i] = res.msg[i];
  }
  Info.joinAddress = res.msg.province + res.msg.city + res.msg.area;
  // console.log(res);
};
getDate();
const onFinish = ({ selectedOptions }) => {
  show.value = false;
  Info.province = selectedOptions[0];
  Info.city = selectedOptions[1];
  Info.area = selectedOptions[2];
  Info.joinAddress = selectedOptions.map((option) => option.text).join("-");
};
const onFailed = (v) => {
  //  console.log(v);
};
const submit = async () => {
  const res = await editAddress(Info);
  showToast(res.msg);
  res.code == 1 ? router.go(-1) : "";
};
</script>
